'use strict'

const { Controller } = require('egg')

class AdminController extends Controller {
  /**
   * 系统首页
   */
  async home() {
    const { ctx } = this
    const { admin } = ctx.state

    const adminRole = await ctx.model.AdminRole.findOne({
      _id: admin.roleId,
    })

    const menuFilter = {
      systemType: admin.systemType,
      isOpen: true,
    }

    // 指定菜单
    if (!adminRole.isAdmin) menuFilter._id = [...adminRole.halfMenuIds, ...adminRole.menuIds]

    let [menuList, defaultMenu, systemConfig] = await Promise.all([
      ctx.model.AdminMenu.tree({
        filter: menuFilter,
        sort: {
          isTop: 'Desc',
          rank: 'ASC',
        },
      }),
      ctx.model.AdminMenu.findOne({
        ...menuFilter,
        $and: [{ path: { $ne: null } }, { path: { $ne: '' } }],
      }).sort({
        isTop: 'Desc',
        rank: 'ASC',
      }),
      ctx.service.config.getConfigByType('system'),
    ])

    if (!defaultMenu) defaultMenu = menuList[0]

    ctx.body = {
      code: 0,
      msg: 'success',
      data: {
        menuList,
        defaultMenu,
        systemConfig,
      },
    }
  }

  /**
   * @api {post} /api/login [系统] 登录
   * @apiGroup 通用
   * @apiParam {String} username 用户名称
   * @apiParam {String} password  用户密码
   *
   * @apiSuccessExample {json} Success-Response:
    {
        "code": 0,
        "msg": "成功",
    }
   */
  async login() {
    const { ctx } = this
    const { body } = ctx.request

    const returnData = await ctx.service.systemUser.login({
      username: body.username,
      password: body.password,
    })

    if (ctx.session) ctx.session.admin = returnData

    ctx.body = {
      code: 0,
      msg: '登录成功',
      data: returnData,
    }
  }

  // 获取系统配置
  async systemSetting() {
    const { ctx } = this

    const returnData = await ctx.service.config.getConfigByType('system')

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  // 设置系统配置
  async saveSystemSetting() {
    const { ctx } = this
    const configType = 'system'

    await ctx.model.Config.updateOne(
      { configType },
      { configType, config: ctx.request.body },
      {
        upsert: true, // 不存在插入
        setDefaultsOnInsert: true, // 允许插入默认值
      }
    )

    await this.service.config.deleteConfigCache(configType)

    ctx.body = {
      code: 0,
      msg: 'success',
    }
  }

  /**
   * @api {get} /system/dict [系统] 字典列表
   * @apiGroup System
   * 
   * @apiParam {Boolean} [isArray=true] 按原始数组形式返回
   *
   * @apiSuccessExample {json} Success-Response:
    {
        "code": 0,
        "msg": "success",
        "data": {
            "deviceModel": {
                "55": "55寸设备"
            },
            "bannerPosition": {
                "splash": "开屏",
            },
            "controlBannerPosition": {
                "home": "首页"
            }
        }
    }
   */
  async dictList() {
    const { ctx } = this
    const { query } = ctx
    const isArray = query.query != false ? true : false

    this.ctx.body = {
      code: 0,
      msg: 'success',
      data: this.service.dict[isArray ? 'getDictAllArr' : 'getDictAll'](),
    }
  }

  /**
     * @api {get} /system/dict/:key [系统] 字典详情
     * @apiGroup System
     * 
     * @apiParam {Boolean} [isArray=true] 按原始数组形式返回
     *
     * @apiSuccessExample {json} Success-Response:
      {
          "code": 0,
          "msg": "success",
          "data": [
              {
                  "label": "55",
                  "value": "55寸设备"
              }
          ]
      }
     */
  async dictDetail() {
    const { ctx } = this
    const { query } = ctx
    const isArray = query.query != false ? true : false
    const key = this.ctx.params.id

    this.ctx.body = {
      code: 0,
      msg: 'success',
      data: this.service.dict[isArray ? 'getDictArr' : 'getDict'](key),
    }
  }

  /**
   * @apiDefine AdminCommon
   * @apiVersion 0.0.0
   *
   * @apiHeader {String} Authorization 用户token
   *
   * @apiSuccess {Int} code 状态码 <br /> 0、成功 <br /> 1、失败
   * @apiSuccess {String} msg  消息
   * @apiSuccess {Object} data 返回数据
   *
   */
}

module.exports = AdminController
